#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Tue Jul 23 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
from datetime import datetime, timedelta

from location.models import Location
from .base import BaseDispatcher


class LocationDispatcher(BaseDispatcher, Location):

    def __init__(self):
        BaseDispatcher.__init__(self)
        Location.__init__(self)

    def start(self):
        try:
            self.send_info()
        except Exception as e:
            print(e)
        self.dump_status()

    def send_info(self):
        print(f'=== Started at {datetime.now()}')

        # 从字典中获得开始的时间  并整理查询的开始时间和结束时间
        start_time = self.current_status.get("vehiclePosition")

        docu = self.cursor.get_collection(datetime.now().strftime('%Y%m')).aggregate(
            [
                {"$match": {
                    "vehicle_license_number": {"$in": ["沪D83092", "沪EG9631", "沪ED8973", "沪D31650"]},  # dev
                    # "vehicle_license_number": {"$in": self.vehicle_infos.values()},  # prod
                    "start_timespan": start_time},
                 },
                {"$sort": {"gps.occurred_time": -1}},
                {"$group": {"_id": "$vehicle_license_number",
                            "gps": {"$first": "$gps"},
                            "count": {"$sum": 1}
                            }
                 },
            ],
            allowDiskUse=True
        )
        position_info_dict = {}
        for i in docu:
            data = {
                "dispatchNo": "",
                "vno": i["_id"],
                "color": "黄",
                "type": 0,
                "coordinate": "GCJ02",  # 高德火星坐标
                "source": self.VENDER_CODE,
                "reserve1": "",
                "reserve2": ""
            }
            position_info_list = []

            for info in i['gps']:
                position_info = {
                    "lng": info['longtitude'],
                    "lat": info['latitude'],
                    "time": str(info['occurred_time'])
                }
                position_info.update(data)
                position_info_list.append(position_info)
                position_info_dict[i['_id']] = position_info_list  # 以车牌为键，五分钟内的所有gps为值

            # 根据每辆车的长度，进行筛选
        all_position_list = []
        for car in position_info_dict.values():
            if len(car) // 10 >= 1:
                average_num = len(car) // 10
                car = car[::average_num]
                all_position_list.extend(car)
            else:
                all_position_list.extend(car)

        # 获得消息列表，发送数据
        self.send("vehiclePosition", all_position_list)

        # 更新一下时间
        self.current_status['vehiclePosition'] = start_time + timedelta(minutes=5)
